use std::fs;
use std::io::{prelude::*, BufReader};
use std::net::{TcpListener, TcpStream};
use std::thread;

fn main() {
    let listener = TcpListener::bind("127.0.0.1:8080").unwrap();

    for stream in listener.incoming() {
        let stream = stream.unwrap();

        thread::spawn(|| {
            handle_request(stream);
        });
    }
}

fn handle_request(mut stream: TcpStream) {
    // 处理请求
    let buf_reader = BufReader::new(&stream);

    let http_request: Vec<_> = buf_reader
        .lines()
        .map(|result| result.unwrap())
        .take_while(|line| !line.is_empty())
        .collect();

    println!("requrest:{:#?}", http_request);
    let (res_status, file_name) = if http_request[0] == "GET / HTTP/1.1" {
        ("HTTP/1.1 200 OK\r\n", "index.html")
    } else {
        ("HTTP/1.1 404 NOT FOUND\r\n", "404.html")
    };
    let contents = fs::read_to_string(file_name).unwrap();

    let len = contents.len();

    let res = format!("{res_status}Content-Length:{len}\r\n\r\n{contents}");

    stream.write_all(res.as_bytes()).unwrap();
}
